package cn.gaaidou.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author Martin
 * @date 2021/7/5 16:04
 */
@Slf4j
public class JdkSerializationUtil {

    /**
     * JDK序列化对象
     *
     * @param o
     * @return
     */
    public static byte[] serialize(Object o) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(o);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("JDK序列化对象出现异常, 异常原因: {}", e.getMessage(), e);
            throw new RuntimeException("JDK序列化对象出现异常");
        }

    }


    /**
     * JDK反序列化对象
     *
     * @param data
     * @return
     */
    public static Object deserialize(byte[] data) {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        try (ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.error("JDK反序列化对象出现异常, 异常原因: {}", e.getMessage(), e);
            throw new RuntimeException("JDK反序列化对象出现异常");
        }

    }
}
